<template>
	<view class="container">
		<view class="avatar-wrapper">
			<image class="avatar" :src="avatarUrl" v-if="avatarUrl!=''"></image>
			<uni-icons type="contact" color="#000" size="85" v-else></uni-icons>
		</view>

		<uni-forms ref="form" :modelValue="formData" :rules="rules">
			<uni-forms-item name="phone">
				<uni-easyinput type="number" @input="input" focus maxlength="11" v-model="formData.phone"
					placeholder="请输入对方的手机号" />
			</uni-forms-item>
		</uni-forms>
		<view class="btn-submit">
			<button type="default" :disabled="submiting" @click="submit">发送邀请</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				fid: '',
				avatarUrl: '',
				formData: {
					phone: ''
				},
				timer: null,
				submiting: false,
				rules: {
					phone: {
						// name 字段的校验规则
						rules: [{
								required: true,
								errorMessage: '请输入手机号',
							},
							// 对name字段进行长度验证
							{
								minLength: 11,
								maxLength: 11,
								errorMessage: '请输入正确的手机号',
							}
						],
						validateTrigger: 'submit'
					}
				}
			};
		},

		onLoad(options) {
			this.fid = options.fid
		},

		methods: {

			// 请求
			sendInvitation() {
				this.submiting = true
				setTimeout(() => {
					uni.$api.fridge.invite({
						phoneNumOfFriend: this.formData.phone,
						fid: this.fid
					})
					this.submiting = false
				}, 500)
				uni.navigateBack({
					delta: 1
				})
			},
			async getAvatarByPhone() {
				this.avatarUrl = await uni.$api.user.getAvatarByPhone(this.formData.phone)
			},

			// 事件处理
			input() {
				if (this.formData.phone.length != 11)
					return
				// 清除 timer 对应的延时器
				clearTimeout(this.timer)
				// 重新启动一个延时器，并把 timerId 赋值给 this.timer
				this.timer = setTimeout(async () => {
					this.getAvatarByPhone()
				}, 500)
			},
			submit() {
				this.$refs.form.validate().then(res => {
					this.sendInvitation()
				}).catch(err => {
					uni.$showMsg(err[0].errorMessage)
				})
			},
		}
	}
</script>

<style lang="scss">
	.container {
		height: 100vh;
		background-color: #fff;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.avatar-wrapper {
		padding: 0;
		width: 85px !important;
		margin-top: 40px;
		margin-bottom: 40px;

		.avatar {
			display: block;
			border-radius: 8px;
			width: 85px;
			height: 85px;
		}
	}

	.uni-forms {
		width: 85%;
	}

	.btn-submit {
		width: 85%;
		margin-top: 18px;

		>button {
			background-color: #94bfff;
			color: #fff;
		}

	}
</style>
